import os
from dotenv import load_dotenv
from langgraph.prebuilt import chat_agent_executor
from langchain_tavily import TavilySearch
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI

load_dotenv()

# 1.创建模型
model = ChatOpenAI(
    model='qwen-plus',
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# result = model.invoke([HumanMessage(content='上海天气怎么样？')])
# print(result)

# LangChain内置的Tavily工具可以作为搜索引擎工具
search = TavilySearchResults(max_results=2)
print(search.invoke('上海天气怎么样？'))

# LangChainDeprecationWarning:
# The class `TavilySearchResults` was deprecated in LangChain 0.3.25 and will be removed in 1.0.
# An updated version of the class exists in the :class:`~langchain-tavily package and should be used instead.
# To use it run `pip install -U :class:`~langchain-tavily` and import as `from :class:`~langchain_tavily import TavilySearch``.
new_search = TavilySearch(max_results=2)

tools = [new_search]
# 给模型绑定工具
# model_with_tools = model.bind_tools([search])
# model_with_tools = model.bind_tools(tools)

# 模型可以推理是否需要调用工具来完成用户的任务
# result1 = model_with_tools.invoke([HumanMessage(content='侬好啊，我是Gary！北京天气怎么样？')])
# print(f'Model_Result_content: {result1.content}')
# print(f'Tools_Result_content: {result1.tool_calls}')
#
# result2 = model_with_tools.invoke([HumanMessage(content='梵蒂冈的首都是哪里？')])
# print(f'Model_Result_content: {result2.content}')
# print(f'Tools_Result_content: {result2.tool_calls}')

# 创建代理
agent_executor = chat_agent_executor.create_tool_calling_executor(model, tools)
resp1 = agent_executor.invoke({'messages': [HumanMessage(content='侬好啊，我是Gary！北京天气怎么样？')]})
print(resp1['messages'])
resp2 = agent_executor.invoke({'messages': [HumanMessage(content='梵蒂冈的首都是哪里？')]})
print(resp2['messages'])
